package com.ibm.iisp.common.web.springmvc.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Set;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.iisp.common.web.springmvc.ExposedResourceBundleMessageSource;

@Controller
public class CommonjsController {
	Logger log = LoggerFactory.getLogger(getClass());
	@Inject
	HierarchicalMessageSource messageSource;
	@Inject
	ObjectMapper oMapper;

	@Value("${app.sessiontime:30}")
	int sessionTime;
	@Value("${file.download.root:/files.htm?path=}")
	String fileDownloadRoot;
	@Value("${app.context.path:NULL}")
	String contextPath;
	@Value("${app.env.name:DEV}")
	String envName;

	@RequestMapping("/commonjs.js")
	public String commonjs1(HttpServletRequest request, HttpServletResponse response, Model model) {
		return commonjs(request, response, model);
	}

	@RequestMapping("/assets/commonjs")
	public String commonjs(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("sessionTime", sessionTime);
		model.addAttribute("fileDownloadRoot", fileDownloadRoot);
		Locale locale = RequestContextUtils.getLocale(request);
		ExposedResourceBundleMessageSource mSource = (ExposedResourceBundleMessageSource) messageSource;
		Set<Object> mkeys = mSource.getKeys(locale);
		model.addAttribute("envName", envName);
		if ("NULL".equals(contextPath)) {
			contextPath = request.getContextPath();
		}
		model.addAttribute("contextPath", contextPath);
		HashMap<String, String> mLabels = new HashMap<>();
		for (Object okey : mkeys) {
			String key = (String) okey;
			mLabels.put(key, mSource.getMessage(key, null, locale));
		}
		try {
			oMapper.writeValueAsString(mLabels);
			model.addAttribute("mLabels", mLabels);
		} catch (JsonProcessingException e) {
			log.error("Convert to json error:{}", mLabels, e);
		}
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/javascript");
		return "/common.th.js";
	}
}
